﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace Solution.Provide.Utilities
{
    class HttpClientHelper
    {
        /// <summary>
        /// HttpClient发起一个 get 请求
        /// </summary>
        /// <param name="url">请求地址，参数拼接在后面</param>
        /// <param name="headers">http头部键值对</param>
        /// <returns></returns>
        static async Task<string> HttpClientGetAsyncTask(string url, Dictionary<string, string> headers = null)
        {
            //创建HttpClient（注意传入HttpClientHandler）
            var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };

            using (var http = new HttpClient(handler))
            {
                if (headers != null)
                {
                    foreach (var item in headers)
                    {
                        http.DefaultRequestHeaders.Add(item.Key, item.Value);
                    }
                }

                //http.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                //await异步等待回应
                var response = await http.GetAsync(url);
                //确保HTTP成功状态值
                response.EnsureSuccessStatusCode();

                //await异步读取最后的JSON（注意此时gzip已经被自动解压缩了，因为上面的AutomaticDecompression = DecompressionMethods.GZip）
                return await response.Content.ReadAsStringAsync();
            }
        }


        /// <summary>
        /// HttpClient实现Post请求,默认contentType
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="param">参数</param>
        /// <param name="headers">请求头</param>
        /// <returns></returns>
        static async Task<string> HttpClientPostAsyncTask(string url, Dictionary<string, string> param, Dictionary<string, string> headers = null)
        {
            //设置HttpClientHandler的AutomaticDecompression
            var handler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
            //创建HttpClient（注意传入HttpClientHandler）
            using (var http = new HttpClient(handler))
            {
                //使用FormUrlEncodedContent做HttpContent
                var content = new FormUrlEncodedContent(param);
                if (headers != null)
                {
                    foreach (var item in headers)
                    {
                        content.Headers.Add(item.Key, item.Value);
                    }
                }
                //await异步等待回应
                var response = await http.PostAsync(url, content);
                //确保HTTP成功状态值
                response.EnsureSuccessStatusCode();
                //await异步读取最后的JSON（注意此时gzip已经被自动解压缩了，因为上面的AutomaticDecompression = DecompressionMethods.GZip）
                return await response.Content.ReadAsStringAsync();
            }
        }

        /// <summary>
        /// HttpClient实现Post请求,设置 contentType 为 application/json
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="param">参数</param>
        /// <param name="headers">请求头</param>
        public static async Task<string> HttpClientPostJsonAsyncTask(string url, Dictionary<string, string> param, Dictionary<string, string> headers = null)
        {
            var requestJson = JsonConvert.SerializeObject(param);

            HttpContent httpContent = new StringContent(requestJson);
            httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            if (headers != null)
            {
                foreach (var item in headers)
                {
                    httpContent.Headers.Add(item.Key, item.Value);
                }
            }
            var httpClient = new HttpClient();
            var responseJson = await httpClient.PostAsync(url, httpContent);
            var result = responseJson.Content.ReadAsStringAsync().Result;

            //var sites = JArray.Parse(result);
            //sites.ToList().ForEach(x => System.Console.WriteLine(x["Title"] + "：" + x["Uri"]));
            return result;
        }

    }
}
